package com.zqxq.auth.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zqxq.auth.entity.module.Code;
import com.zqxq.auth.entity.module.Result;
import com.zqxq.auth.entity.po.Role;
import com.zqxq.auth.entity.po.UserAdmin;
import com.zqxq.auth.mapper.RoleMapper;
import com.zqxq.auth.service.IFuncService;
import com.zqxq.auth.service.IRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/01/18 17:14
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private IFuncService funcService;
    @Override
    public Result getRoleList(Integer currentPage, Integer pageSize, Long role_id) {
        if (currentPage == null || currentPage < 1) {
            currentPage = 1;
        }
        if (pageSize == null || pageSize < 0) {
            pageSize = 10;
        }
        long offset = (currentPage - 1) * pageSize;
        String role_ids = this.getChildrenRoleString(role_id.toString());
        List<Map<String, Object>> roleList = baseMapper.getRoleList(offset, pageSize, role_ids);
        Long total = baseMapper.getRoleListTotal(role_ids);
        Map data = new HashMap();
        data.put("records", roleList);
        data.put("total", total);
        return new Result(data);
    }

    @Override
    public Result saveRole(Role role, String funcIds, UserAdmin userAdmin) {
        if (role == null) {
            return new Result(Code.FAIL, "非法入参");
        }
        if (role.getRole_id() == null) {
            String role_name = role.getRole_name();
            if (role_name == null) {
                return new Result(Code.FAIL,"角色名称不能为空");
            }
            if (!validRoleName(role_name, role.getRole_id())) {
                return new Result(Code.FAIL,"角色名称重复");
            }
            role.setParent_role_id(userAdmin.getRole_id());
        }

        String[] funcArr = null;
        if (funcIds != null) {
            funcArr = funcIds.split(",");
            int funcNum = funcService.getFuncNumByIds(funcIds, userAdmin.getRole_id());
            if (funcArr.length != funcNum) {
                return new Result(Code.FAIL, "功能id集，入参错误");
            }
        }
        role.setUpdate_time(new Timestamp(System.currentTimeMillis()));
        this.insertOrUpdate(role);
        Long role_id = role.getRole_id();
        this.updateRoleFunc(role_id, funcArr, funcIds);

        return new Result();
    }

    /**
     * 修改角色功能
     * @param role_id
     * @param funcArr
     * @param funcIds
     */
    private void updateRoleFunc(Long role_id, String[] funcArr, String funcIds) {
        baseMapper.deleteRoleFuncByRoleId(role_id);//删除角色功能
        baseMapper.deleteChildrenFunc(this.getChildrenRoleString(role_id.toString()), funcIds);//删除子角色未包含在funcIds的功能
        if (funcArr != null) {//为角色新增权限
            StringBuffer sb = new StringBuffer();
            for(String str : funcArr) {
                sb.append("(").append(role_id).append(",").append(str).append(")").append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            baseMapper.insertRoleFuncs(sb.toString());
        }
    }

    /**
     * 获取角色及其子角色id,以“,”分割
     * @param parent_role_ids
     * @return
     */
    public String getChildrenRoleString(String parent_role_ids) {
        String ids = baseMapper.getgetChildrenRoleString(parent_role_ids);
        if (ids == null) {
            return parent_role_ids;
        } else {
            parent_role_ids += "," + getChildrenRoleString(ids);
        }
        return parent_role_ids;
    }

    @Override
    public Result updateRoleStatus(Long role_id, Integer role_status) {
        if (role_status == 0) {//禁用
            baseMapper.updateRoleAndChildrenStatus(getChildrenRoleString(role_id.toString()), role_status);
        } else {//启用
            Role role = new Role();
            role.setRole_id(role_id);
            role.setRole_status(role_status);
            baseMapper.updateById(role);
        }

        return new Result();
    }

    @Override
    public Result isRoleNamePass(String role_name, Long role_id) {
        if (StringUtils.isEmpty(role_name)) {
            return new Result(Code.FAIL, "角色名不能为空");
        }
        return new Result(validRoleName(role_name, role_id));
    }

    @Override
    public Result getUsingRoleList(UserAdmin userAdmin) {
        String role_ids = this.getChildrenRoleString(userAdmin.getRole_id().toString());
        List<Map<String, Object>> roleList = baseMapper.getUsingRoleList(role_ids);
        Map data = new HashMap();
        data.put("records", roleList);
        return new Result(data);
    }

    @Override
    public Result getRoleFuncByRoleId(Long role_id) {
        if (role_id == null) {
            return new Result(Code.FAIL, "角色id，不能为空");
        }
        String func_ids = baseMapper.getFuncIdsByRoleId(role_id);
        return new Result(func_ids);
    }

    private boolean validRoleName(String role_name, Long role_id) {
        Role role1 = new Role();
        role1.setRole_name(role_name);
        Wrapper wrapper = new EntityWrapper(role1);
        List<Role> list = baseMapper.selectList(wrapper);
        if (list == null || list.isEmpty()) {
            return true;
        }
        if (list.size() < 2) {
            if (role_id == list.get(0).getRole_id()) {
                return true;
            }
        }
        return false;
    }
}
